package com.horsecoder.im.common.protocol.context;

import com.horsecoder.common.error.Assert;
import com.horsecoder.im.common.protocol.context.identity.ChannelIdentity;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author: Zhu yuhan
 * Email: zhuyuhan2333@qq.com
 * Date: 2022/3/16 9:17 下午
 **/
public class SessionSocketHolder {

    private final static Map<String, Channel> NIO_USER_SESSION_MAP = new ConcurrentHashMap<>();

    private final static Map<ChannelIdentity, Channel> NIO_SOCKET_CHANNEL_MAP = new ConcurrentHashMap<>();

    public static Channel getSocketChannel(String identity) {
        Channel result = null;
        result = NIO_USER_SESSION_MAP.entrySet().stream().filter((entry) -> entry.getKey().equals(identity)).findFirst().map(Map.Entry::getValue).orElse(null);
        Assert.notNull(result, "SOCKET_ERROR");
        return result;
    }

    public static void putSocketChannel(String identity, Channel channel) {
        NIO_USER_SESSION_MAP.put(identity, channel);
    }

    public static void putChannelIdentity(ChannelIdentity channelIdentity, Channel channel) {
        NIO_SOCKET_CHANNEL_MAP.put(channelIdentity, channel);
    }

    public static void putChannelIdentity(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ChannelIdentity channelIdentity = new ChannelIdentity(channel.remoteAddress(), channel.id().asLongText());
        NIO_SOCKET_CHANNEL_MAP.put(channelIdentity, channel);
    }

    public static Channel getChannelByIdentity(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ChannelIdentity channelIdentity = new ChannelIdentity(channel.remoteAddress(), channel.id().asLongText());
        return NIO_SOCKET_CHANNEL_MAP.get(channelIdentity);
    }

    public static void removeChannelByIdentity(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ChannelIdentity channelIdentity = new ChannelIdentity(channel.remoteAddress(), channel.id().asLongText());
        NIO_SOCKET_CHANNEL_MAP.remove(channelIdentity);
    }
}
